#!/bin/bash
#
# Pulley hashing routines
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 18 November 2013
#
#   Copyright 2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#


# Hash routines to try when using best_hash
declare -g STD_HASH_ROUTINES="sha512sum sha256sum sha1sum md5sum mod_time"


## mod_time <file>
##
## Returns the modification time of <file> in seconds since the epoch.
## Returns 0 if successful, non-zero on error.
##
function mod_time() {
	attr -c %Y "$1"
	return $?
}


## best_hash [--all] <file>
##
## Computes the best available hash value for <file>. Returns 0 if successful,
## non-zero if an error occurs.
##
## Echoes the best hash found. If the optional --all argument is given,
## echoes all available hashes, from best to worst, one per line.
##
function best_hash() {
	local all=0
	local status=1
	local value=""
	
	if [[ "$1" == "--all" ]]; then
		all=1
		shift
	fi
	
	for alg in STD_HASH_ROUTINES; do
		if is_callable "${alg}"; then
			value=$("${alg}" "$1")
			status=$?
			
			if ((status == 0)); then
				echo "${value}"
				[ ${all} -eq 0 ] && break
			fi
		fi
	done
	
	return ${status}
}


## check_hash <hash> <file>
##
## Checks to see if <file> has the hash value <hash>, using each hash routine
## in order. Stops if a match is found. Returns 0 on success, non-zero if the
## the hash cannot be validated.
##
function check_hash() {
	local status=1
	local value=""
	
	for alg in STD_HASH_ROUTINES; do
		if is_callable "${alg}"; then
			value=$("${alg}" "$2")
			if [[ "${value}" == "$1" ]]; then
				status=0
				break
			fi
		fi
	done
	
	return ${status}
}
